package argo.hot100.mqtrix;

import java.util.ArrayList;
import java.util.List;

public class SpiralOrder {


    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix == null) {
            return null;
        }
        List<Integer> res = new ArrayList<>();
        int leftX = 0, leftY = 0, rightX = matrix.length - 1, rightY = matrix[0].length - 1;

        while (leftX <= rightX && leftY <= rightY) {


            for (int y = leftY; y <= rightY; y++) {
                res.add(matrix[leftX][y]);
            }

            for (int x = leftX + 1; x <= rightX; x++) {
                res.add(matrix[x][rightY]);
            }


            if (leftX < rightX && leftY < rightY) {

                for (int y = rightY - 1; y > leftY; y--) {
                    res.add(matrix[rightX][y]);
                }

                for (int x = rightX; x > leftX; x--) {
                    res.add(matrix[x][leftY]);
                }
            }

            leftX++;
            leftY++;
            rightX--;
            rightY--;
        }

        return res;

    }
}
